package cn.liuhuan.qiniu.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;


@Component
public class QiniuCloudUtil {
    // 设置需要操作的账号的AK和SK
    private static final String ACCESS_KEY = "QsyyZvhOhZIkxEPbIREeNLCn6BVBRUiunhuPJtvX";
    private static final String SECRET_KEY = "JKl5rF7SlAAlftdGJ8hB3cVqQhuoxRg3tPqchgth";

    // 要上传的空间
    private static final String bucketname = "ykun";


    // 密钥
    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

//    private static final String DOMAIN = "s3306n8fy.bkt.clouddn.com/";


    public String getUpToken(String fileName) {
        StringMap putPolicy = new StringMap();
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize)}");
        long expireSeconds = 3600;
        String upToken = auth.uploadToken(bucketname, null, expireSeconds, putPolicy);
        System.out.println("upToken = " + upToken);
        return upToken;
    }

    // 普通上传
    public String upload(MultipartFile file,String fileName) throws IOException {
        // 创建上传对象
        Configuration cfg = new Configuration(Region.huadongZheJiang2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            byte[] uploadBytes =file.getBytes();
            String token =getUpToken(fileName);
            try {
                Response response = uploadManager.put(uploadBytes, fileName, token);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            }catch (QiniuException e){
                Response r = e.response;
                // 请求失败时打印的异常的信息
                System.out.println(r.toString());
                try {
                    // 响应的文本信息
                    System.out.println(r.bodyString());
                } catch (QiniuException e1) {
                    // ignore
                }
            }
        } catch (UnsupportedEncodingException ex) {
        }
        return null;
    }


}
